15. Exercise: Setup and Teardown

ANDK L4 26 Set Up-Tear Down SC

Pick the right lifecycle state

QUIZ QUESTION::

If I want the timer running only when the activity is visible, during what lifecycle method should I call start() and stop()?

ANSWER CHOICES:



Timer

Activity

I should start the timer in:

I should stop the timer in:

SOLUTION:

Timer

Activity

I should start the timer in:

I should stop the timer in:

ANDK L4 28 Avoiding Lifecycle Memory Leaks SC

Now it’s your turn to complete this exercise yourself.

For this exercise, you will create a timer class that counts every second when the app is on screen.

**1. Uncomment the DessertTimer class. **

**2. Initialize DessertTimer in onCreate callback of Main Activity: **

dessertTimer = DessertTimer()

**3. Start DessertTimer in onStart and stop it in onStop callback: **

dessertTimer.startTimer()
dessertTimer.stopTimer()

If you want to start at this step, you can download this exercise code from: Step.03-Exercise-Setup-and-tear-down.

You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.

Once you’re done, you can check your solution against the solution we’ve provided here Step.03-Solution-Setup-and-tear-down or using this git diff.

Task Description:

Check the steps below as you implement them to complete this exercise.

Task List:

Task Feedback:

Great job!

Solution: Step.03-Solution-Setup-and-tear-down or using this git diff